package com.lbmb.photodrawaimanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lbmb.photodrawaimanager.service.HuoShanService;
import com.lbmb.photodrawaimanager.utils.FileOpeationUtils;
import com.lbmb.photodrawaimanager.utils.OssUtils;
import com.sun.deploy.net.HttpResponse;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import com.volcengine.service.visual.model.request.VisualEnhancePhotoV2Request;
import com.volcengine.service.visual.model.request.VisualFaceFusionMovieGetResultRequest;
import com.volcengine.service.visual.model.request.VisualFaceFusionMovieSubmitTaskRequest;
import com.volcengine.service.visual.model.request.VisualJPCartoonRequest;
import com.volcengine.service.visual.model.response.VisualEnhancePhotoV2Response;
import com.volcengine.service.visual.model.response.VisualFaceFusionMovieGetResultResponse;
import com.volcengine.service.visual.model.response.VisualFaceFusionMovieSubmitTaskResponse;
import com.volcengine.service.visual.model.response.VisualJPCartoonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * @author hanWang
 * @Title:
 * @Package
 * @Description:
 * @date 2023/8/56:36 下午
 */
@Service
public class HuoShanServiceImpl implements HuoShanService {

//    @Value("${huoshan.accessKey}")
//    String accessKey;
//
//    @Value("${huoshan.secretKey}")
//    String secretKey;
    @Autowired
    OssUtils ossUtils;
    IVisualService visualService = VisualServiceImpl.getInstance();

    @Autowired
    public HuoShanServiceImpl(@Value("${huoshan.accessKey}") String accessKey, @Value("${huoshan.secretKey}")String secretKey){
        visualService.setAccessKey(accessKey);
        visualService.setSecretKey(secretKey);
    }



    @Override
    public void downloadManHuaFengImg(HttpResponse response1, String filePath,Boolean isCheck,String carToonType,String imgUrl) {

        VisualJPCartoonRequest req = new VisualJPCartoonRequest();
        //req.setImageBase64(FileOpeationUtils.getBase64("https://lbmb-center.oss-cn-shanghai.aliyuncs.com/2023/08/057d74924f3f9549b791890256502ed44f1.jpg"));
        req.setImageBase64(FileOpeationUtils.getBase64(imgUrl));
        //req.setCartoonType("jpcartoon");
        req.setCartoonType(carToonType);
        req.setDoRisk(isCheck);
        // req.setCartoonType("jpcartoon_head"); // jpcartoon_head | jpcartoon | hkcartoon
        // req.setRotation(1);
        File file = new File("file.txt");





        try {
            VisualJPCartoonResponse response = visualService.jpCartoon(req);
            String image = response.getData().getImage();
            ossUtils.uploadInputStream(generateImage1(image,"/"),"jpg");

           // generateImage(image,"/Users/wanghan/Desktop/huoshan_Img/");
            System.out.println(JSON.toJSONString(response));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public String downloadManHuaFengImg(Boolean isCheck, String carToonType, String imgUrl) {

//        IVisualService visualService = VisualServiceImpl.getInstance();
//
//        // call below method if you dont set ak and sk in ～/.vcloud/config
//        visualService.setAccessKey(accessKey);
//        visualService.setSecretKey(secretKey);

        VisualJPCartoonRequest req = new VisualJPCartoonRequest();
        //req.setImageBase64(FileOpeationUtils.getBase64("https://lbmb-center.oss-cn-shanghai.aliyuncs.com/2023/08/057d74924f3f9549b791890256502ed44f1.jpg"));
        req.setImageBase64(FileOpeationUtils.getBase64(imgUrl));
        //req.setCartoonType("jpcartoon");
        req.setCartoonType(carToonType);
        if ("jpcartoon_head".equals(carToonType)) {
            req.setRotation(1);
        }
        req.setDoRisk(isCheck);
        // req.setCartoonType("jpcartoon_head"); // jpcartoon_head | jpcartoon | hkcartoon
        // req.setRotation(1);





        try {
            VisualJPCartoonResponse response = visualService.jpCartoon(req);
            String image = response.getData().getImage();
            String filePath = ossUtils.uploadInputStream(generateImage1(image, "/"), "jpg");

            // generateImage(image,"/Users/wanghan/Desktop/huoshan_Img/");
            System.out.println(JSON.toJSONString(response));
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String makeFaceFusionMovie(String imgUrl, String movieUrl) {
//        IVisualService visualService = VisualServiceImpl.getInstance();
//
//        // call below method if you dont set ak and sk in ～/.vcloud/config
//        visualService.setAccessKey(accessKey);
//        visualService.setSecretKey(secretKey);
        //提交任务
        VisualFaceFusionMovieSubmitTaskRequest req = new VisualFaceFusionMovieSubmitTaskRequest();
        // 固定值
        req.setReqKey("facefusionmovie_standard");
        req.setImageUrl(imgUrl);
        req.setVideoUrl(movieUrl);
        // 是否开启美颜
        req.setEnableFaceBeautify(true);

        /**
         * 指定视频中待融合人脸的图像URL地址。当视频中有多个人脸时，通过该参数提供的人脸清晰正面照，可以指定要融合人脸的人物，该参数填写待融合人脸的图像URL地址。当视频中仅有一人，或需要融合不特定某人的人脸时，该参数可填写空字符串。多个人脸时用逗号分隔，顺序与image_url一致。	顺序需一致
         */
        req.setRefImgUrl("true");
        /**
         * source_similarity	可选	String	人脸相似度: 范围[0~1]，越大越相似.
         * 0: 不换脸
         * 1: 最大相似度。默认1（同原来效果）
         */
        req.setSourceSimilarity("true");

        try {
            VisualFaceFusionMovieSubmitTaskResponse response = visualService.faceFusionMovieSubmitTask(req);
            String taskId = response.getData().getTaskId();
            // 异步获取视频文件
            // 查询任务
        VisualFaceFusionMovieGetResultRequest reAsy = new VisualFaceFusionMovieGetResultRequest();
        reAsy.setReqKey("facefusionmovie_standard");
        reAsy.setTaskId(taskId);

        try {
            VisualFaceFusionMovieGetResultResponse asyResponse = visualService.faceFusionMovieGetResult(reAsy);
            String respData = asyResponse.getData().getRespData();
            JSONObject parse = (JSONObject)JSONObject.parse(respData);
            //生成的视频url
            String video_url = parse.getString("video_url");
            System.out.println(JSON.toJSONString(asyResponse));
        } catch (Exception e) {
            e.printStackTrace();
        }

            System.out.println(JSON.toJSONString(response));
            return "返回成功了";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public String makeEnhancePhotoV2() {
//        IVisualService visualService = VisualServiceImpl.getInstance();
//
//        // call below method if you dont set ak and sk in ～/.vcloud/config
//        visualService.setAccessKey(accessKey);
//        visualService.setSecretKey(secretKey);

        VisualEnhancePhotoV2Request req = new VisualEnhancePhotoV2Request();
        req.setReqKey("lens_lqir");

        ArrayList <String> binaryData = new ArrayList<>();
        binaryData.add("image_base64");
        req.setBinaryDataBase64(binaryData);

        try {
            VisualEnhancePhotoV2Response response = visualService.enhancePhotoV2(req);
            System.out.println(JSON.toJSONString(response));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static InputStream generateImage1(String base64, String path) {
        // 解密
        try {
            // 图片分类路径+图片名+图片后缀
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1);
            // 解密，解密的结果是一个byte数组
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgbytes = decoder.decode(base64);
            for (int i = 0; i < imgbytes.length; ++i) {
                if (imgbytes[i] < 0) {
                    imgbytes[i] += 256;
                }
            }

            // 保存图片
            InputStream input = new ByteArrayInputStream(imgbytes);
//
//            out.write(imgbytes);
//            out.flush();
//            out.close();
            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
            return input;
        } catch (Exception e) {
            return null;
        }
    }


    public static String generateImage(String base64, String path) {
        // 解密
        try {
            // 图片分类路径+图片名+图片后缀
            String imgClassPath = path.concat(UUID.randomUUID().toString()).concat(".jpg");
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1);
            // 解密，解密的结果是一个byte数组
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgbytes = decoder.decode(base64);
            for (int i = 0; i < imgbytes.length; ++i) {
                if (imgbytes[i] < 0) {
                    imgbytes[i] += 256;
                }
            }

            // 保存图片
            OutputStream out = new FileOutputStream(imgClassPath);
            FileInputStream fileInputStream = new FileInputStream(imgClassPath);

            out.write(imgbytes);
            out.flush();
            out.close();
            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
            return imgClassPath;
        } catch (IOException e) {
            return null;
        }
    }
}
